package io.renren.modules.pms.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.pms.service.impl.QiniuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Controller  // 修改：从@RestController改为@Controller
@RequestMapping("/pms/qiniu")  // 修改：路径改为/pms/qiniu
public class QiniuController {

    @Autowired
    private QiniuService qiniuService;

    /**
     * 页面跳转 - 新增这个方法
     */
    @GetMapping("")
    @RequiresPermissions("pms:qiniu:list")
    public String qiniuPage() {
        return "modules/pms/qiniu";  // 对应 templates/modules/pms/qiniu.html
    }

    /**
     * 获取上传凭证 - REST API
     */
    @GetMapping("/token")
    @ResponseBody  // 新增：因为现在是@Controller，需要标注返回JSON的方法
    public R getUploadToken(@RequestParam(required = false) String bucket) {
        String token = qiniuService.getUploadToken(bucket);
        return R.ok().put("token", token);
    }

    /**
     * 上传文件 - REST API
     */
    @PostMapping("/upload")
    @ResponseBody
    @RequiresPermissions("pms:qiniu:upload")
    public R upload(@RequestParam("file") MultipartFile file,
                    @RequestParam(required = false) String bucket) {
        // 原有代码保持不变
        if (file.isEmpty()) {
            return R.error("请选择要上传的文件");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            String fileKey = generateFileKey(originalFilename);
            String key = qiniuService.uploadFile(file.getBytes(), fileKey, bucket);
            String url = qiniuService.getFileUrl(key);

            Map<String, Object> result = new HashMap<>();
            result.put("key", key);
            result.put("url", url);
            result.put("name", originalFilename);
            result.put("size", file.getSize());

            return R.ok().put("data", result);
        } catch (Exception e) {
            return R.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件 - REST API
     */
    @PostMapping("/delete")
    @ResponseBody
    @RequiresPermissions("pms:qiniu:delete")
    public R delete(@RequestBody Map<String, String> params) {
        // 原有代码保持不变
        String fileName = params.get("fileName");
        String bucket = params.get("bucket");

        if (StringUtils.isEmpty(fileName)) {
            return R.error("文件名不能为空");
        }

        boolean result = qiniuService.deleteFile(fileName, bucket);
        return result ? R.ok("删除成功") : R.error("删除失败");
    }

    /**
     * 获取文件列表 - REST API
     */
    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("pms:qiniu:list")
    public R listFiles(@RequestParam(required = false) String prefix,
                       @RequestParam(required = false) String marker,
                       @RequestParam(required = false) String bucket) {
        // 原有代码保持不变
        FileListing fileListing = qiniuService.listFiles(prefix, marker, bucket);

        List<Map<String, Object>> fileList = new ArrayList<>();
        if (fileListing.items != null) {
            for (FileInfo fileInfo : fileListing.items) {
                Map<String, Object> fileMap = new HashMap<>();
                fileMap.put("key", fileInfo.key);
                fileMap.put("size", fileInfo.fsize);
                fileMap.put("putTime", fileInfo.putTime);
                fileMap.put("mimeType", fileInfo.mimeType);
                fileMap.put("url", qiniuService.getFileUrl(fileInfo.key));
                fileList.add(fileMap);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("items", fileList);
        result.put("marker", fileListing.marker);

        return R.ok().put("data", result);
    }

    private String generateFileKey(String originalFilename) {
        if (StringUtils.isEmpty(originalFilename)) {
            throw new RRException("文件名不能为空");
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (StringUtils.isEmpty(suffix)) {
            suffix = "";
        }
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }
}